<template>
  <div>
    <div id="components-form-demo-advanced-search">
      <a-row :gutter="24" style="margin-bottom: 15px">
        <a-col :span="6">
          订单编号：<a-input
          :maxLength="128"
            v-model="searchData.orderNumber"
            style="width: 60%"
          />
        </a-col>
        <a-col :span="6">
          收件人 ：
          <a-input :maxLength="128" style="width: 60%" v-model="searchData.recipient" />
        </a-col>
        <a-col :span="6">
          商品SKU： <a-input :maxLength="128" style="width: 60%" v-model="searchData.sku" />
        </a-col>
        <a-col :span="6">
          <div v-show="!expand">
            <a-button type="primary" class="searchBtn" @click="searchBtn">
              查询
            </a-button>
            <a-button
              style="margin: 0 10px"
              type="primary"
              class="searchBtn"
              @click="reset"
            >
              重置
            </a-button>
            <a
              :style="{ marginRight: '8px', fontSize: '14px' }"
              @click="expand = !expand"
            >
              {{ expand ? "折叠" : "展开" }}
              <a-icon :type="expand ? 'up' : 'down'" />
            </a>
          </div>
          <div v-show="expand">
            物流单号：<a-input
            :maxLength="128"
              style="width: 60%"
              v-model="searchData.waybillNo"
            />
          </div>
        </a-col>
      </a-row>
      <a-row :gutter="24" v-show="expand">
        <a-col :span="6">
          出库仓库：
          <a-select
            show-search
            option-filter-prop="children"
            style="width: 60%"
            :filter-option="filterOption"
            v-model="searchData.warehouseId"
            allowClear
          >
            <a-select-option value="" key="1"> 全部 </a-select-option>
            <a-select-option
              :value="item.warehouseId"
              v-for="item in clientWareHouse"
              :key="item.warehouseId"
            >
              {{ item.titleName }}
            </a-select-option>
          </a-select>
        </a-col>
        <a-col :span="6">
          更新时间：
          <a-range-picker
            v-model="applyDate"
            style="width: 60%"
            @change="onChangeApplyDate"
          >
            <a-icon slot="suffixIcon" style="color: #3eae7c" type="calendar" />
          </a-range-picker>
        </a-col>
        <a-col :span="6">
          <div v-show="expand">
            <a-button type="primary" class="searchBtn" @click="searchBtn">
              查询
            </a-button>
            <a-button
              style="margin: 0 10px"
              type="primary"
              class="searchBtn"
              @click="reset"
            >
              重置
            </a-button>
            <a
              :style="{ marginRight: '8px', fontSize: '14px' }"
              @click="expand = !expand"
            >
              {{ expand ? "折叠" : "展开" }}
              <a-icon :type="expand ? 'up' : 'down'" />
            </a>
          </div>
        </a-col>
        <a-col :span="6"> </a-col>
      </a-row>
    </div>
    <div class="action" style="margin-top: 10px">
      <span>
        <a-button
          type="primary"
          class="top-btn"
          style="background: #409cff; color: #ffff; border: none"
          @click="showAddModal"
        >
          新建出库申请
        </a-button>
      </span>
      <span>
        <a-button
          @click="excelBtn"
          type="primary"
          class="top-btn"
          style="background: #409cff; color: #ffff; border: none; margin: 0 8px"
        >
          导出订单
        </a-button>
      </span>
      <span>
        <a-dropdown
          :trigger="['click']"
          slot="tabBarExtraContent"
          v-if="OutboundKeys === '5'"
        >
          <a-menu slot="overlay" @click="handleMenuClick">
            <a-menu-item key="yesSign"> 选中签收服务</a-menu-item>
            <a-menu-item key="noSign"> 取消签收服务 </a-menu-item>
            <a-menu-item key="updateDefer"> 选中暂缓处理 </a-menu-item>
            <a-menu-item key="import"> 设置自有运单 </a-menu-item>
            <a-menu-item key="cancelEctn"> 取消自有运单 </a-menu-item>
            <a-menu-item key="logistics"> 设置物流商 </a-menu-item>
            <a-menu-item key="submit"> 批量提交 </a-menu-item>
            <a-menu-item key="batchDel"> 批量删除 </a-menu-item>
          </a-menu>
          <a-button
            style="
              background: #409cff;
              color: #ffff;
              border: none;
              margin-right: 2rem;
            "
          >
            批量操作 <a-icon type="down" />
          </a-button>
        </a-dropdown>
      </span>
      <span v-if="logisticsFlag && OutboundKeys === '5'">
        物流平台/物流商：
        <a-select
          placeholder="请选择物流商"
          size="small"
          show-search
          option-filter-prop="children"
          style="width: 12rem"
          @change="handleChangeLogistics"
          v-model="logistics.logisticsName"
        >
          <a-select-option
            v-for="item in logisticsArray"
            :value="item.id"
            :key="item.id"
            :logisticsPlatform="item.logisticsPlatform"
            :serviceName="item.serviceName"
            :sysLogisticsId="item.sysLogisticsId"
            :sysLogisticsServiceItemId="item.sysLogisticsServiceItemId"
          >
            <a-tooltip>
              <template slot="title">
                {{ item.serviceName }}/{{ item.logisticsPlatform }}
              </template>
              {{ item.serviceName }}/{{ item.logisticsPlatform }}
            </a-tooltip>
          </a-select-option>
        </a-select>
      </span>
      <span v-if="logisticsFlag && OutboundKeys === '5'">
        物流方式：
        <a-select
          size="small"
          show-search
          option-filter-prop="children"
          style="width: 10rem"
          @change="changeLogisticsServiceArry"
        >
          <a-select-option
            v-for="item in logisticsServiceArry"
            :value="item.wayName"
            :sysLogisticsServiceWayTenantId="
              item.sysLogisticsServiceWayTenantId
            "
            :key="item.sysLogisticsServiceWayTenantId"
          >
            {{ item.wayName }}
          </a-select-option>
        </a-select>
      </span>
      <span v-if="logisticsFlag && OutboundKeys === '5'">
        <a-button type="primary" @click="logisticsBtch"> 确认 </a-button>
      </span>
    </div>
    <a-spin tip="Loading..." :spinning="spinning">
      <a-tabs default-active-key="5" @change="callback">
        <a-tab-pane key="5">
          <span slot="tab">
            <a-badge
              :count="statecount === null ? 0 : statecount.submitCount"
              :offset="[15, 0]"
              >待提交
            </a-badge>
          </span>
          <OutboundTable
            v-if="OutboundKeys === '5'"
            :tableData="tableData"
            OutboundKeys="待提交"
            :getOutboundTableList="getOutboundTableList"
            :getStateCount="getStateCount"
            @selectedRowKeys="selectedRowKeys"
          />
        </a-tab-pane>
        <a-tab-pane key="15" force-render>
          <span slot="tab">
            <a-badge
              :count="statecount === null ? 0 : statecount.disposeCount"
              :offset="[15, 0]"
              >待仓库处理
            </a-badge>
          </span>
          <OutboundTable
            v-if="OutboundKeys === '15'"
            :tableData="tableData"
            OutboundKeys="待仓库处理"
            :getOutboundTableList="getOutboundTableList"
            :getStateCount="getStateCount"
            @selectedRowKeys="selectedRowKeys"
          />
        </a-tab-pane>
        <a-tab-pane key="25">
          <span slot="tab">
            <a-badge
              :count="statecount === null ? 0 : statecount.processedCount"
              :offset="[15, 0]"
              >正在处理
            </a-badge>
          </span>
          <OutboundTable
            v-if="OutboundKeys === '25'"
            :tableData="tableData"
            OutboundKeys="正在处理"
            :getOutboundTableList="getOutboundTableList"
            :getStateCount="getStateCount"
            @selectedRowKeys="selectedRowKeys"
          />
        </a-tab-pane>
        <a-tab-pane key="35">
          <span slot="tab">
            <a-badge
              :count="statecount === null ? 0 : statecount.shippedCount"
              :offset="[15, 0]"
              >已发货
            </a-badge>
          </span>
          <OutboundTable
            v-if="OutboundKeys === '35'"
            :tableData="tableData"
            OutboundKeys="已发货"
            :getOutboundTableList="getOutboundTableList"
            :getStateCount="getStateCount"
            @selectedRowKeys="selectedRowKeys"
          />
        </a-tab-pane>
        <a-tab-pane key="45">
          <span slot="tab">
            <a-badge
              :count="statecount === null ? 0 : statecount.exceptionCount"
              :offset="[15, 0]"
              >异常订单
            </a-badge>
          </span>
          <OutboundTable
            v-if="OutboundKeys === '45'"
            :tableData="tableData"
            OutboundKeys="异常订单"
            :getOutboundTableList="getOutboundTableList"
            :getStateCount="getStateCount"
            @selectedRowKeys="selectedRowKeys"
          />
        </a-tab-pane>
        <a-tab-pane key="55">
          <span slot="tab">
            <a-badge
              :count="statecount === null ? 0 : statecount.processingCount"
              :offset="[15, 0]"
              >暂缓处理
            </a-badge>
          </span>
          <OutboundTable
            v-if="OutboundKeys === '55'"
            :tableData="tableData"
            OutboundKeys="暂缓处理"
            :getOutboundTableList="getOutboundTableList"
            :getStateCount="getStateCount"
            @selectedRowKeys="selectedRowKeys"
          />
        </a-tab-pane>
      </a-tabs>
    </a-spin>
    <!-- 分页器 -->
    <div style="margin: 20px 0; text-align: center">
      <a-config-provider>
        <a-pagination
          show-size-changer
          :pageSizeOptions="['10', '20', '30']"
          :show-total="
            (total) => `${$t('m.page.Total')} ${total} ${$t('m.page.items')}`
          "
          @showSizeChange="showChange"
          :buildOptionText="
            (props) => ` ${props.value} ${$t('m.page.a')}/${$t('m.page.page')}`
          "
          show-quick-jumper
          :current="searchData.current"
          :total="total"
          @change="onChangePage"
        />
      </a-config-provider>
    </div>
    <!-- 新增模态框 -->
    <OutboundModal
      :getOutboundTableList="getOutboundTableList"
      :getStateCount="getStateCount"
      :OutboundKeys="OutboundKeys"
    />
    <!-- 批量导入模态框 -->
    <ImportModal
      :getOutboundTableList="getOutboundTableList"
      :getStateCount="getStateCount"
      :selectedKeys="selectedKeys"
    />
  </div>
</template>

<script>
import {
  Outbound_tabList,
  Outbound_statecount,
  Outbound_del,
  OutboundBatchByState_submit,
  OutboundBatchByState_yesSign,
  OutboundBatchByState_noSign,
  OutboundBatchByState_cancelEctn,
  OutboundBatchByState_updateDefer,
  OutboundBatchByState_excel,
  Outbounddel_batchCarrier,
} from "@/apis/clientSide/OrderManage/Outbound";
import { selectTenantIdAllServerName } from "@/apis/common";
import req from "../../../utils/req";
import OutboundTable from "@/components/clientSide/OrderManage/Outbound/OutboundTable.vue";
import OutboundModal from "@/components/clientSide/OrderManage/Outbound/OutboundModal.vue";
import ImportModal from "@/components/clientSide/OrderManage/Outbound/ImportModal.vue";
import moment from "moment";
import { mapState } from "vuex";
export default {
  components: {
    OutboundTable,
    OutboundModal,
    ImportModal,
  },
  created() {
    this.getOutboundTableList();
    this.getStateCount();
  },
  data() {
    return {
      //批量更改物流信息集合
      logistics: {
        logisticsId: null,
        logisticsName: null,
        logisticsService: null,
        logisticsServiceId: null,
      },
      spinning: false,
      applyDate: null,
      expand: false,
      url: "",
      //物流商标杆
      logisticsFlag: false,
      //复选框的值
      selectedKeys: [],
      selectedRows: [],
      // 表头状态气泡数量
      statecount: {},
      tableData: [],
      OutboundKeys: "5",
      total: 5,
      searchData: {
        applyState: "5",
        batchNo: null,
        current: 1,
        ectnNo: null,
        endtDate: null,
        id: null,
        logisticsId: null,
        orderCode: null,
        orderNumber: null,
        recipient: null,
        size: 10,
        startDate: null,
        tenantId: null,
        warehouseId: null,
        waybillNo: null,
        waybillState: null,
      },
      logisticsList: null,
      logisticsServiceArry: null,
    };
  },
  methods: {
    //批量设置物流商
    async logisticsBtch() {
      if (
        this.logistics.logisticsId === null &&
        this.logistics.logisticsService === null
      ) {
        this.$message.error("请选择物流渠道和物流服务后确认！");
        return false;
      }
      let { code } = await Outbounddel_batchCarrier({
        ids: this.selectedKeys,
        logisticsId: this.logistics.logisticsId,
        logisticsName: this.logistics.logisticsName,
        logisticsService: this.logistics.logisticsService,
        logisticsServiceId: this.logistics.logisticsServiceId,
      });
      if (code === "10000") {
        this.logisticsFlag = false;
        this.logistics.logisticsId = null;
        this.logistics.logisticsName = null;
        this.logistics.logisticsService = null;
        setTimeout(() => {
          this.$bus.$emit("clearSelectedKeys");
        });
      }
    },
    // 物流商更改
    async handleChangeLogistics(value, option) {
      this.logistics.logisticsName =
        option.data.attrs.serviceName +
        "/" +
        option.data.attrs.logisticsPlatform;
      this.logistics.logisticsId =
        option.data.attrs.sysLogisticsId +
        "," +
        option.data.attrs.sysLogisticsServiceItemId;
      let { code, responseBody } = await selectTenantIdAllServerName(
        option.data.attrs.sysLogisticsId,
        option.data.attrs.sysLogisticsServiceItemId,
        sessionStorage.getItem("tenantId")
      );
      if (code === "200") {
        this.logisticsServiceArry = responseBody;
      }
    },
    //物流方式更改
    changeLogisticsServiceArry(value, option) {
      this.logistics.logisticsService = value;
      this.logistics.logisticsServiceId =
        option.data.attrs.sysLogisticsServiceWayTenantId;
    },
    reset() {
      let current = this.searchData.current;
      let size = this.searchData.size;
      for (let key in this.searchData) {
        this.searchData[key] = null;
      }
      this.searchData.applyState = this.OutboundKeys;
      this.searchData.current = current;
      this.searchData.size = size;
      this.searchData.waybillState = "";
      this.searchData.warehouseId = "";
      this.applyDate = null;
      this.getOutboundTableList();
    },
    disabledDate(current) {
      // Can not select days before today and today
      return (
        current && current < moment(this.searchData.startDate).endOf("day")
      );
    },
    //批量导出
    async excelBtn() {
      if (this.selectedKeys.length === 0) {
        this.$message.error("请勾选要导出的数据！");
        return false;
      }
      let res = await OutboundBatchByState_excel(
        this.searchData.applyState,
        this.selectedKeys
      );
      req.exportFile("出库申请", res);
    },
    //查询接口
    searchBtn() {
      this.getOutboundTableList();
    },
    // 接收子传过来的复选框
    selectedRowKeys(val, selectedRows) {
      this.selectedKeys = val;
      this.selectedRows = selectedRows;
    },
    //选项卡更改
    callback(key) {
      this.searchData.current = 1;
      this.selectedKeys = [];
      this.OutboundKeys = key;
      this.searchData.applyState = key;
      this.getOutboundTableList();
    },
    //分页器事件
    onChangePage(pageNumber) {
      this.searchData.current = pageNumber;
      this.getOutboundTableList();
    },
    //页码变更
    showChange(size, current) {
      this.searchData.current = size;
      this.searchData.size = current;
      this.getOutboundTableList();
    },
    //批量操作
    handleMenuClick(e) {
      let _this = this;
      if (e.key === "batchDel") {
        if (this.selectedKeys.length <= 0) {
          this.$message.error("请勾选需要操作的数据！");
          return false;
        }
        this.$confirm({
          title: "确定要删除这些数据吗?",
          cancelText: "取消",
          okText: "确认",
          onOk() {
            return new Promise((resolve) => {
              setTimeout(async () => {
                let { code } = await Outbound_del(_this.selectedKeys);
                if (code === "10000") {
                  resolve();
                }
              }, 1000);
            }).then(() => {
              _this.getStateCount();
              _this.getOutboundTableList();
              _this.selectedKeys = [];
            });
          },
        });
      } else if (e.key === "submit") {
        if (this.selectedKeys.length <= 0) {
          this.$message.error("请勾选需要操作的数据！");
          return false;
        }
        this.$confirm({
          title: "确定提交这些数据吗?",
          cancelText: "取消",
          okText: "确认",
          onOk() {
            return new Promise((resolve) => {
              setTimeout(async () => {
                let { code } = await OutboundBatchByState_submit(
                  _this.selectedKeys
                );
                if (code === "10000") {
                  resolve();
                }
              }, 1000);
            }).then(() => {
              _this.getStateCount();
              _this.getOutboundTableList();
              _this.selectedKeys = [];
            });
          },
        });
      } else if (e.key === "logistics") {
        if (this.selectedKeys.length <= 0) {
          this.$message.error("请勾选需要操作的数据！");
          return false;
        }
        this.logisticsFlag = true;
      } else if (e.key === "import") {
        this.showImportModal();
      } else if (e.key === "yesSign") {
        if (this.selectedKeys.length <= 0) {
          this.$message.error("请勾选需要操作的数据！");
          return false;
        }
        this.$confirm({
          title: "确定选择签收服务吗?",
          cancelText: "取消",
          okText: "确认",
          onOk() {
            return new Promise((resolve) => {
              setTimeout(async () => {
                let { code } = await OutboundBatchByState_yesSign(
                  _this.selectedKeys
                );
                if (code === "10000") {
                  resolve();
                }
              }, 1000);
            }).then(() => {
              // _this.getStateCount();
              _this.getOutboundTableList();
            });
          },
        });
      } else if (e.key === "noSign") {
        if (this.selectedKeys.length <= 0) {
          this.$message.error("请勾选需要操作的数据！");
          return false;
        }
        this.$confirm({
          title: "确定要取消签收服务吗?",
          cancelText: "取消",
          okText: "确认",
          onOk() {
            return new Promise((resolve) => {
              setTimeout(async () => {
                let { code } = await OutboundBatchByState_noSign(
                  _this.selectedKeys
                );
                if (code === "10000") {
                  resolve();
                }
              }, 1000);
            }).then(() => {
              // _this.getStateCount();
              _this.getOutboundTableList();
            });
          },
        });
      } else if (e.key === "cancelEctn") {
        if (this.selectedKeys.length <= 0) {
          this.$message.error("请勾选需要操作的数据！");
          return false;
        }
        this.$confirm({
          title: "确定要取消自有运单吗?",
          cancelText: "取消",
          okText: "确认",
          onOk() {
            return new Promise((resolve) => {
              setTimeout(async () => {
                let { code } = await OutboundBatchByState_cancelEctn(
                  _this.selectedKeys
                );
                if (code === "10000") {
                  resolve();
                }
              }, 1000);
            }).then(() => {
              _this.getOutboundTableList();
            });
          },
        });
      } else if (e.key === "updateDefer") {
        if (this.selectedKeys.length <= 0) {
          this.$message.error("请勾选需要操作的数据！");
          return false;
        }
        this.$confirm({
          title: "确定要暂缓处理这些订单吗?",
          cancelText: "取消",
          okText: "确认",
          onOk() {
            return new Promise((resolve) => {
              setTimeout(async () => {
                let { code } = await OutboundBatchByState_updateDefer(
                  "55",
                  _this.selectedKeys
                );
                if (code === "10000") {
                  resolve();
                }
              }, 1000);
            }).then(() => {
              _this.getStateCount();
              _this.getOutboundTableList();
            });
          },
        });
      }
    },
    handleChange(value) {
      console.log(`selected ${value}`);
    },
    // 到仓时间
    onChangeApplyDate(date, dateString) {
      this.searchData.startDate = dateString[0];
      this.searchData.endtDate = dateString[1];
      date;
    },
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text
          .toLowerCase()
          .indexOf(input.toLowerCase()) >= 0
      );
    },
    // 显示新增模态框
    showAddModal() {
      setTimeout(() => {
        this.$bus.$emit("showOutboundAddModal");
      }, 50);
    },
    // 显示批量导入模态框
    showImportModal() {
      setTimeout(() => {
        this.$bus.$emit("showOutboundImportModal", this.selectedRows);
      }, 50);
    },
    // 获取表格数据
    async getOutboundTableList() {
      this.spinning = true;
      let { code, responseBody } = await Outbound_tabList(this.searchData);
      if (code === "200") {
        this.total = responseBody.total * 1;
        let { records } = responseBody;
        this.tableData = JSON.stringify(records);
        this.tableData = JSON.parse(this.tableData);
        this.tableData.forEach((item, i) => {
          item.IDX = i + this.searchData.current * this.searchData.size - 9;
          item.updateTime = item.updateTime
            ? item.updateTime.replace("T", "  ")
            : "";
          item.createTime = item.createTime
            ? item.createTime.replace("T", "  ")
            : "";
          if (item.applyState === "5") {
            item.applyState = "待提交";
          } else if (item.applyState === "15") {
            item.applyState = "待仓库处理";
          } else if (item.applyState === "25") {
            item.applyState = "正在处理";
          } else if (item.applyState === "35") {
            item.applyState = "已发货";
          } else if (item.applyState === "45") {
            item.applyState = "订单异常";
          } else if (item.applyState === "55") {
            item.applyState = "暂缓处理";
          }
        });
        this.spinning = false;
      }
    },
    //获取表头统计
    async getStateCount() {
      let res = await Outbound_statecount();
      //   console.log(res);
      this.statecount = res.responseBody;
    },
  },
  computed: {
    ...mapState(["clientWareHouse"]),
    ...mapState(["logisticsArray"]),
  },
};
</script>

<style lang="less" scoped>
.searchBtn {
  background: #fff;
  color: #3eae7c;
  text-shadow: none;
}
.searchBtn:hover {
  background: #3eae7c;
  color: #fff;
}
.action {
  span {
    margin: 0 5px;
  }
}
input {
  width: auto;
}
.top-search {
  span {
    margin: 5px 10px;
    input {
      width: 7rem;
    }
  }
}
.top-btn {
  background: #fff;
  color: #3eae7c;
  text-shadow: none;
}
.top-btn:hover {
  background: #3eae7c;
  color: #fff;
}
</style>
